import React, {useState, useEffect} from "react";

interface VerifyCodeButtonProps {
    onGetCode: () => void; // 点击获取验证码时的回调函数
    disabled: boolean;
    setDisabled: React.Dispatch<React.SetStateAction<boolean>>
}

const VerifyCodeButton: React.FC<VerifyCodeButtonProps> = ({onGetCode, disabled, setDisabled, ...props}) => {
    const [time, setTime] = useState(60); // 倒计时时间


    // 点击按钮时的处理逻辑
    const handleClick = () => {
        if (!disabled) {
            onGetCode(); // 触发获取验证码的回调
            setTime(60); // 重置倒计时时间
        }
    };

    // 倒计时逻辑
    useEffect(() => {
        if (time > 0 && disabled) {
            const timer = setTimeout(() => {
                setTime(time - 1);
            }, 1000);
            return () => clearTimeout(timer);
        } else if (time === 0) {
            setDisabled(false); // 倒计时结束后解除按钮禁用
        }
    }, [time, disabled, setDisabled]);

    return (
        <button style={{backgroundColor: disabled ? "var(--gray-50)" : "", cursor: disabled ? "not-allowed" : ""}}
                className='z-button' type="button"
                onClick={handleClick} disabled={disabled} {...props}>
            {disabled ? `${time}秒后重新获取` : "获取验证码"}
        </button>
    );
};

export default VerifyCodeButton;